//
//  FeedImageCell.swift
//  图片动态Cell
//
//  Created by smile on 2019/7/7.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

class FeedImageCell: BaseFeedCell {
    static let NAME = "FeedImageCell"

    
    /// 图片列表控件
    @IBOutlet weak var collectionView: UICollectionView!
    
    /// 列表控件高
    @IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
    
    /// 列表图片
    var dataArray:[Resource] = []
    
    /// 显示多少列
    var spanCount:CGFloat = 3
    
    /// 图片预览点击回调
    var onImageClick:((_ images:[UIImage],_ index:Int)->Void)!
    
    override func initViews() {
        super.initViews()
        
        //这列表数据源和代理
        collectionView.dataSource=self
        collectionView.delegate=self
        
        //注册ImageCell
        collectionView.register(UINib(nibName: ImageCell.NAME, bundle: nil), forCellWithReuseIdentifier: ImageCell.NAME)
    }
    
    override func bindData(_ data:Feed) {
        super.bindData(data)
        
        self.next()
    }
    
    func next() {
        print("FeedImageCell next:\(data.content)")
        //根据数量计算colltionView高度
        //规则为图片张数大于4，显示3列
        //图片张数大于1，显示2列
        //其他情况显示1列
        
        //先获取当前cell宽度，因为图片是矩形
        //高等于宽
        //let width=collectionView.frame.size.width
        //let width=self.frame.width-20-45-20
        
        //前面的方法无法保证一定获取到
        //CollectionView自动布局计算后的宽度
        //所以这里通过获取屏幕的宽度（没有缩放的尺寸）
        //减去相关的宽度
        //就能得到CollectionView的宽度
        let width = UIScreen.main.bounds.width-20-45-20
        
        //计算显示列数
        if data.images!.count>4 {
            spanCount = 3
        }else if data.images!.count>1 {
            spanCount = 2
        } else {
            spanCount = 1
        }
        
        //计算每一个图片宽度
        let subCellWidth = width/spanCount
        
        //计算可以显示多少行
        let rows = ceil(CGFloat(data.images!.count)/spanCount)
        
        //collectionView高度等于=行数*行高
        let collectionViewHeight = rows * subCellWidth
        
        //更改collectionView高度
        self.collectionViewHeight.constant = collectionViewHeight
        
        //移除原来的图片
        dataArray.removeAll()
        
        //将动态图片添加到列表
        dataArray=dataArray+data.images!
        
        //重新加载数据
        collectionView.reloadData()
    }
    
}

// MARK:- UICollectionViewDelegateFlowLayout代理相关方法
/// 主要用来设置Cell的一些间距
extension FeedImageCell:UICollectionViewDelegateFlowLayout{
    
    /// 返回Cell和CollectionView的间距
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - collectionViewLayout: <#collectionViewLayout description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    /// 返回每个Cell的行间距
    /// 也就是每行之间的间距
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - collectionViewLayout: <#collectionViewLayout description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    /// 返回每个Cell的列间距
    /// 也就是每列之间的间距
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - collectionViewLayout: <#collectionViewLayout description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

// MARK: - 列表数据源和代理
extension FeedImageCell:UICollectionViewDataSource,UICollectionViewDelegate{
    
    /// 有多少个
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    /// 返回cell
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //获取cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageCell.NAME, for: indexPath) as! ImageCell
        
        //绑定数据
        cell.bindData(dataArray[indexPath.row])
        
        //返回cell
        return cell
    }
    
    /// 返回cell宽高
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - collectionViewLayout: <#collectionViewLayout description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.width/spanCount
        
        return CGSize(width: width, height: width)
    }
    
    /// cell点击
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - indexPath: <#indexPath description#>
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("FeedImageCell didSelectItemAt:\(indexPath.row)")
        
        //装所有图片
        var images:[UIImage] = []
        
        //获取到当前Cell所有Image
        let cells = collectionView.visibleCells as! [ImageCell]
        
        for cell in cells {
            //遍历将image放到数据组
            
            //也可以只是将图片图片地址返回
            //但既然图片已经显示了
            //所以直接使用image也可以
            //还减少了二次加载
            //虽然图片加载框架中有缓存
            //直接使用image理论上性能要好一点
            images.append(cell.ivImage.image!)
        }
        
        //回调图片预览方法
        onImageClick(images,indexPath.row)
        
    }
}
